package com.ruoyi.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 公共工具类
 *
 * @author qiancheng
 * @date 2025-03-05
 */
@Component
public class CommentUtil {
    private static long companyId;
    private static String uploadPath;

    @Value("${company_id}")
    public void setCompanyId(long value) {
        companyId = value;
    }
    @Value("${file.upload.path}")
    public  void setUploadPath(String value) {
        uploadPath = value;
    }

    /**
     * 初始化工厂ID
     * @param object
     * @param <T>
     * @author qiancheng
     * @since 2025-03-06
     */
    public static <T> void resetCompanyId(T object) {
        try {
            Method setCompanyId = object.getClass().getMethod("setCompanyId", Long.class);
            setCompanyId.invoke(object, companyId);
        } catch (Exception e) {
            throw new RuntimeException("设置companyId失败", e);
        }
    }

   /**
     * 判断并初始化工厂ID
     * @param object
     * @param <T>
     * @author qiancheng
     * @since 2025-03-11
     */
    public static <T> void resetCompanyIdIfNull(T object) {
        try {
            // 尝试获取对象的getCompanyId方法
            Method getCompanyIdMethod = object.getClass().getMethod("getCompanyId");
            // 调用getCompanyId方法获取当前对象的companyId值
            Long currentCompanyId = (Long) getCompanyIdMethod.invoke(object);
            // 判断当前对象的companyId值是否为null，若为null才进行赋值
            if (currentCompanyId == null) {
                resetCompanyId(object);
            }
        } catch (Exception e) {
            throw new RuntimeException("设置companyId失败", e);
        }
    }

    /**
     * 上传文件
     * @param file
     * @throws IOException
     */
    public static String upLoadFile(MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            // 检查文件大小
            if (file.getSize() > 20 * 1024 * 1024) {
                throw new RuntimeException("文件大小不能超过20MB!");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 生成新的文件名（时间戳+原文件名）
            String newFileName = System.currentTimeMillis() + "_" + fileName;

            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 构建完整的文件路径
            File dest = new File(uploadPath + File.separator + newFileName);
            // 保存文件
            file.transferTo(dest);
            return newFileName;
        }
        return null;
    }

    /**
     * 上传多个文件
     * @param files
     * @throws IOException
     */
    public static String upLoadFiles(MultipartFile[] files) throws IOException, InterruptedException {
        // 处理多个文件上传，用逗号分隔文件名
        if (files != null && files.length > 0) {
            List<String> uploadedFileNames = new ArrayList<>();

            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    // 检查文件大小
                    if (file.getSize() > 30 * 1024 * 1024) {
                        throw new RuntimeException("文件大小不能超过30MB!");
                    }
                    // 获取文件名
                    String fileName = file.getOriginalFilename();
                    // 生成新的文件名（时间戳+原文件名）
                    String newFileName = System.currentTimeMillis() + "_" + fileName;

                    // 确保上传目录存在
                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    // 构建完整的文件路径
                    File dest = new File(uploadPath + File.separator + newFileName);

                    // 保存文件
                    file.transferTo(dest);
                    uploadedFileNames.add(newFileName);

                    // 添加小延时避免文件名冲突
                    Thread.sleep(1);

                }
            }

            // 将上传成功的文件名用逗号连接
            if (!uploadedFileNames.isEmpty()) {
                return String.join(",", uploadedFileNames);
            }
        }

        return null;
    }

}
